package com.uy.cuantoconocesdeuruguay;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.datatypes.UploadImageEnvelope;
import com.uy.cuantoconocesdeuruguay.dialogs.ErrorOccurredDialogUtils;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;
import com.uy.cuantoconocesdeuruguay.view.LockableScrollView;

public class UploadImage extends BaseActivity {
	private LockableScrollView mScrollView;
	private float height;
	private static final int IMAGE_FROM_CAMERA = 1;	
	private static final int IMAGE_FROM_GALLERY = 2;
	private List<EditText> editTexts = new LinkedList<EditText>();
	private Bitmap mImageBitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_image_step2);
		if (savedInstanceState != null) {
			return;
		}
		height = getResources().getDisplayMetrics().heightPixels;
		mScrollView = (LockableScrollView)findViewById(R.id.uploadScroll);
		
		LinearLayout uploadScroll_layout = (LinearLayout)findViewById(R.id.uploadScroll_layout);		
		boolean isTablet = getResources().getBoolean(R.bool.isTablet);
		if (isTablet){
			uploadScroll_layout.setBackgroundResource(R.drawable.tiled_suggest_image_tablets_bg);
		}
		Drawable background = uploadScroll_layout.getBackground();
		background.setAlpha(221);
		mScrollView.setScrollingEnabled(false);
		scaleLayouts();
		previousStep2(null);
		mScrollView.postInvalidate();
		ImageView cameraIcon = (ImageView)findViewById(R.id.takePictureIcon);
		cameraIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadImageFromCamera();				
			}
		});
		ImageView galleryPictureIcon = (ImageView)findViewById(R.id.galleryPictureIcon);
		galleryPictureIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadImageFromGallery();				
			}
		});		
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		previousStep2(null);
		mScrollView.postInvalidate();
	}
	public void nextStep1(View view){
		mScrollView.post(new Runnable() {     
			public void run() { 
				mScrollView.smoothScrollTo(0, (int) height);
			} 
		});
		hideKeyboard();
	}

	public void nextStep2(View view){
		EditText correctWord 	= (EditText)findViewById(R.id.correctWord);
		setFocusLost(correctWord);
		mScrollView.post(new Runnable() {     
			public void run() {     	
				mScrollView.smoothScrollTo(0, (int) (2*height));
			} 
		});		
		hideKeyboard();
	}

	public void previousStep2(View view){
		EditText correctWord 	= (EditText)findViewById(R.id.correctWord);
		setFocusLost(correctWord);
		mScrollView.post(new Runnable() {     
			public void run() {     	
				mScrollView.smoothScrollTo(0, 0);
			} 
		});
		hideKeyboard();		
	}
//
	private void hideKeyboard(){
		InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
		for (EditText ed : editTexts){
			imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
		}
	}
	private void setFocusLost(View view) {
		view.setFocusableInTouchMode(false);
		view.setFocusable(false);
		view.setFocusableInTouchMode(true);
		view.setFocusable(true);
	}
	
	private void setFocusLostAll(){
		EditText question 	= (EditText)findViewById(R.id.question);
		setFocusLost(question);
		EditText correctAnswer 	= (EditText)findViewById(R.id.correctAnswer);
		setFocusLost(correctAnswer);
		EditText incorrectAnswer1 	= (EditText)findViewById(R.id.incorrectAnswer1);
		setFocusLost(incorrectAnswer1);
		EditText incorrectAnswer2 	= (EditText)findViewById(R.id.incorrectAnswer2);
		setFocusLost(incorrectAnswer2);
		EditText incorrectAnswer3 	= (EditText)findViewById(R.id.incorrectAnswer3);
		setFocusLost(incorrectAnswer3);
		EditText imageInfo = (EditText)findViewById(R.id.imageInfo);
		setFocusLost(imageInfo);
	}

	public void previousStep3(View view){
		EditText question 	= (EditText)findViewById(R.id.question);
		setFocusLost(question);
		EditText correctAnswer 	= (EditText)findViewById(R.id.correctAnswer);
		setFocusLost(correctAnswer);
		EditText incorrectAnswer1 	= (EditText)findViewById(R.id.incorrectAnswer1);
		setFocusLost(incorrectAnswer1);
		EditText incorrectAnswer2 	= (EditText)findViewById(R.id.incorrectAnswer2);
		setFocusLost(incorrectAnswer2);
		EditText incorrectAnswer3 	= (EditText)findViewById(R.id.incorrectAnswer3);
		setFocusLost(incorrectAnswer3);
		EditText imageInfo = (EditText)findViewById(R.id.imageInfo);
		setFocusLost(imageInfo);
		mScrollView.post(new Runnable() {     
			public void run() {     	
				mScrollView.smoothScrollTo(0, (int) height);
			} 
		});	
		hideKeyboard();
	}

	public void nextStep3(View view){
		final EditText word = (EditText)findViewById(R.id.correctWord);
		setFocusLost(word);
		final EditText question = (EditText)findViewById(R.id.question);
		setFocusLost(question);
		final EditText correctAnswer = (EditText)findViewById(R.id.correctAnswer);
		setFocusLost(correctAnswer);
		final EditText incorrectAnswer1 = (EditText)findViewById(R.id.incorrectAnswer1);
		setFocusLost(incorrectAnswer1);
		final EditText incorrectAnswer2 = (EditText)findViewById(R.id.incorrectAnswer2);
		setFocusLost(incorrectAnswer2);
		final EditText incorrectAnswer3 = (EditText)findViewById(R.id.incorrectAnswer3);
		setFocusLost(incorrectAnswer3);
		final EditText imageInfo = (EditText)findViewById(R.id.imageInfo);
		setFocusLost(imageInfo);
		
		if (!checkInputs()){
			if (mImageBitmap == null){
				Toast.makeText(this, getString(R.string.upload_image_image_not_found), Toast.LENGTH_SHORT).show();
				previousStep2(view);
			}else{
				Toast.makeText(this, getString(R.string.upload_image_all_fields_mandatory), Toast.LENGTH_SHORT).show();
			}
			return;
		}
		
		if (!checkWord(word)){
			word.requestFocus();
			previousStep3(view);
			Toast.makeText(this, getString(R.string.upload_image_wrong_word_format), Toast.LENGTH_SHORT).show();
			return;
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.upload_image_send_confirm));	    
	    builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int id) {
//	    		Toast.makeText(UploadImage.this, getString(R.string.upload_image_send_cancel), Toast.LENGTH_SHORT).show();
	    	} 
	    });
	    builder.setPositiveButton(getString(R.string.upload_image_send), new DialogInterface.OnClickListener() {
	    	@Override
	    	public void onClick(DialogInterface dialog, int id) {
	    		UploadImageEnvelope envelope = new UploadImageEnvelope();
	    		
	    		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	    		mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
	    		byte[] b = baos.toByteArray();
	    		String encodedImage = com.uy.cuantoconocesdeuruguay.utiles.Base64.encodeBytes(b);
	    		envelope.setImage(encodedImage.replace(StringPool.PLUS, StringPool.PERCENT_2B));
	    		envelope.setImageExtension(StringPool.JPG);
	    		envelope.setWord(word.getText().toString());
	    		envelope.setQuestion(question.getText().toString());
	    		envelope.setRigthAnswer(correctAnswer.getText().toString());
	    		envelope.setWrongAnswer1(incorrectAnswer1.getText().toString());
	    		envelope.setWrongAnswer2(incorrectAnswer2.getText().toString());
	    		envelope.setWrongAnswer3(incorrectAnswer3.getText().toString());
	    		envelope.setImageInfo(imageInfo.getText().toString());
	    		try {
					ServerConnector.submitPicture(envelope, UploadImage.this) ;
				} catch (ConnectivityException e) {
					ErrorOccurredDialogUtils d = new ErrorOccurredDialogUtils(UploadImage.this, e);
					d.createErrorOccurredPopup();
					e.printStackTrace();
					return;
				}
//	    		Toast.makeText(UploadImage.this, getString(R.string.upload_image_sent_message) , Toast.LENGTH_SHORT).show();
	    		
	    		Intent i = new Intent(getApplicationContext(), MainActivity.class);
//    			i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    			startActivity(i);
    			finish();
	    	} 
	    }); 
		hideKeyboard();
	    builder.setCancelable(true);
	    AlertDialog dialog = builder.create();
	    dialog.show();
	}

	private boolean checkWord(EditText word) {
		if (word.getText().toString().trim().equals(StringPool.BLANK)){
			return false;
		}
		String[] tokens = word.getText().toString().split(StringPool.SPACE);
		if (tokens == null || tokens.length > 4){
			return false;
		}
		for (String token : tokens){
			if (token.length() > 12){
				return false;
			}
		}
		return true;
	}

	private boolean checkInputs() {
		EditText word = (EditText)findViewById(R.id.correctWord);
		EditText question = (EditText)findViewById(R.id.question);
		EditText correctAnswer = (EditText)findViewById(R.id.correctAnswer);
		EditText incorrectAnswer1 = (EditText)findViewById(R.id.incorrectAnswer1);
		EditText incorrectAnswer2 = (EditText)findViewById(R.id.incorrectAnswer2);
		EditText incorrectAnswer3 = (EditText)findViewById(R.id.incorrectAnswer3);
		return !(mImageBitmap == null || 	
				word.getText().toString().equals(StringPool.BLANK) || 
				question.getText().toString().equals(StringPool.BLANK) || 
				correctAnswer.getText().toString().equals(StringPool.BLANK) || 
				incorrectAnswer1.getText().toString().equals(StringPool.BLANK) || 
				incorrectAnswer2.getText().toString().equals(StringPool.BLANK) ||  
				incorrectAnswer3.getText().toString().equals(StringPool.BLANK));
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.upload_image_exit_confirm));
	    builder.setPositiveButton(getString(R.string.upload_image_exit), new DialogInterface.OnClickListener() {
	    	@Override
	    	public void onClick(DialogInterface dialog, int id) {
//	    		Toast.makeText(UploadImage.this, getString(R.string.upload_image_send_cancel), Toast.LENGTH_SHORT).show();
				Intent i = new Intent(getApplicationContext(), MainActivity.class);
//				i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
				finish();
	    	} 
	    });	    
	    builder.setNegativeButton(getString(R.string.upload_image_continue), new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int id) {
	    	} 
	    }); 
	    builder.setCancelable(true);
	    AlertDialog dialog = builder.create();
	    dialog.show();
	}
	
	private void loadImageFromCamera(){
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);		
		File photoFile = null;
		try {
			photoFile = createImageFile();
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
			startActivityForResult(takePictureIntent, IMAGE_FROM_CAMERA);
		} catch (IOException ex) {
			GoogleAnalyticsTracker.trackException(UploadImage.this, ex);
			ex.printStackTrace();
		}		
	}
	private void loadImageFromGallery(){
		Intent intent = new Intent();
	    intent.setType("image/*");
	    intent.setAction(Intent.ACTION_GET_CONTENT);
	    startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_FROM_GALLERY);
	}
	File mCurrentPhotoFile;
	private File createImageFile() throws IOException {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = "JPEG_" + timeStamp + "_";
		File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		mCurrentPhotoFile = File.createTempFile(imageFileName,".jpg",storageDir);
		return mCurrentPhotoFile;
	}
	private void galleryAddPic() {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    Uri contentUri = Uri.fromFile(mCurrentPhotoFile);
	    mediaScanIntent.setData(contentUri);
	    sendBroadcast(mediaScanIntent);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		setFocusLostAll();
		ImageView imageView = ((ImageView)findViewById(R.id.pictureTaken));
		if (resultCode == RESULT_OK){
			if (requestCode == IMAGE_FROM_CAMERA) {
				galleryAddPic();
				try{
					mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(mCurrentPhotoFile));//(Bitmap) extras.get("data");
					float ratioX = (float)mImageBitmap.getWidth()/1080.0f;
					float ratioY = (float)mImageBitmap.getHeight()/1080.0f;
					float maxRatio = Math.max(ratioX, ratioY);
					mImageBitmap = Bitmap.createScaledBitmap(mImageBitmap,(int) (mImageBitmap.getWidth()/maxRatio), (int)(mImageBitmap.getHeight()/maxRatio), true);
					imageView.setImageBitmap(mImageBitmap);
				} catch (FileNotFoundException e) {
					GoogleAnalyticsTracker.trackException(UploadImage.this, e);
				} catch (Exception e) {
					GoogleAnalyticsTracker.trackException(UploadImage.this, e);
				}
			}else if (requestCode == IMAGE_FROM_GALLERY){
	            Uri selectedImageUri = data.getData();
	            if (Build.VERSION.SDK_INT < 19) {
	                String selectedImagePath = getPath(selectedImageUri);
	                mImageBitmap = BitmapFactory.decodeFile(selectedImagePath);
	                float ratioX = (float)mImageBitmap.getWidth()/1080.0f;
					float ratioY = (float)mImageBitmap.getHeight()/1080.0f;
					float maxRatio = Math.max(ratioX, ratioY);
					mImageBitmap = Bitmap.createScaledBitmap(mImageBitmap,(int) (mImageBitmap.getWidth()/maxRatio), (int)(mImageBitmap.getHeight()/maxRatio), true);
					imageView.setImageBitmap(mImageBitmap);
	            }else {
	                ParcelFileDescriptor parcelFileDescriptor;
	                try {
	                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
	                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
	                    mImageBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
	                    parcelFileDescriptor.close();
		                float ratioX = (float)mImageBitmap.getWidth()/1080.0f;
						float ratioY = (float)mImageBitmap.getHeight()/1080.0f;
						float maxRatio = Math.max(ratioX, ratioY);
						mImageBitmap = Bitmap.createScaledBitmap(mImageBitmap,(int) (mImageBitmap.getWidth()/maxRatio), (int)(mImageBitmap.getHeight()/maxRatio), true);
						imageView.setImageBitmap(mImageBitmap);

	                } catch (FileNotFoundException e) {
						GoogleAnalyticsTracker.trackException(UploadImage.this, e);
	                    e.printStackTrace();
	                } catch (Exception e) {
						GoogleAnalyticsTracker.trackException(UploadImage.this, e);
	                    e.printStackTrace();
	                }
	            }
			}
		}
		previousStep2(null);
		mScrollView.postInvalidate();
	} 
	public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
	}
	private void scaleLayouts() {
		float ratioY = height / 800.0f;
		LinearLayout picture = (LinearLayout)findViewById(R.id.pictureLayout);
		LayoutParams layoutParams = picture.getLayoutParams();
		layoutParams.height = (int) (320*ratioY);
		
		int iconSize = 80;

		ImageView nextStepImage1 = (ImageView)findViewById(R.id.nextStep1Icon);
		LayoutParams imageParams1 = nextStepImage1.getLayoutParams();
		imageParams1.height = (int) (iconSize*ratioY);
		imageParams1.width = (int) (iconSize*ratioY);
		
		ImageView nextStepImage2 = (ImageView)findViewById(R.id.nextStep2Icon);
		LayoutParams imageParams2 = nextStepImage2.getLayoutParams();
		imageParams2.height = (int) (iconSize*ratioY);
		imageParams2.width = (int) (iconSize*ratioY);
		
		ImageView nextStepImage3 = (ImageView)findViewById(R.id.nextStep3Icon);
		LayoutParams imageParams3 = nextStepImage3.getLayoutParams();
		imageParams3.height = (int) (iconSize*ratioY);
		imageParams3.width = (int) (iconSize*ratioY);

		ImageView previousStepImage2 = (ImageView)findViewById(R.id.previousStep2Icon);
		LayoutParams imageParams4 = previousStepImage2.getLayoutParams();
		imageParams4.height = (int) (iconSize*ratioY);
		imageParams4.width = (int) (iconSize*ratioY);
		
		ImageView previousStepImage3 = (ImageView)findViewById(R.id.previousStep3Icon);
		LayoutParams imageParams5 = previousStepImage3.getLayoutParams();
		imageParams5.height = (int) (iconSize*ratioY);
		imageParams5.width = (int) (iconSize*ratioY);

		LinearLayout step1Layout = (LinearLayout)findViewById(R.id.step1Layout);
		LayoutParams step1LayoutParams = step1Layout.getLayoutParams();
		step1LayoutParams.height = (int) (height);

		LinearLayout step2Layout = (LinearLayout)findViewById(R.id.step2Layout);
		LayoutParams step2LayoutParams = step2Layout.getLayoutParams();
		step2LayoutParams.height = (int) (height);

		LinearLayout step3Layout = (LinearLayout)findViewById(R.id.step3Layout);
		LayoutParams step3LayoutParams = step3Layout.getLayoutParams();
		step3LayoutParams.height = (int) (height);

        EditText ed;
        ed = (EditText)findViewById(R.id.correctWord);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.imageInfo);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.question);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.correctAnswer);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.incorrectAnswer1);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.incorrectAnswer2);
        editTexts.add(ed);
        ed = (EditText)findViewById(R.id.incorrectAnswer3);
        editTexts.add(ed);
	}

	@Override
	public void trackScreen() {
		GoogleAnalyticsTracker.trackScreen(this, "Sugerir imagen");
	}
}
